home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / msoftapp.zip / SORT2.CPP < prev    next >
C/C++ Source or Header  |  1993-06-01  |  2KB  |  95 lines

  1. ////////////////////////////////////////////////////////////////
  2. // Sort program re-written with generic "comparable" objects
  3. //
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <iostream.h>
  8.  
  9. //////////////////
  10. // Abstract "comparable" object
  11. //
  12. class CmpObj {
  13.     static int QSortFn(const void* v1, const void* v2);
  14. public:
  15.     static void Sort(CmpObj** array, int len);
  16.  
  17.     // pure virtual function: each derived class 
  18.     // must provide its own implementation.
  19.     virtual int compare(CmpObj* c2) = 0;
  20. };
  21.  
  22. //////////////////
  23. // Private static function passed to qsort works for
  24. // all class derived from CmpObj, since "compare" is virtual
  25. //
  26. int CmpObj::QSortFn(const void* v1, const void* v2)
  27. {
  28.     CmpObj* c1 = *(CmpObj**)v1;
  29.     CmpObj* c2 = *(CmpObj**)v2;
  30.  
  31.     // call class-specific virtual compare function
  32.     return c1->compare(c2);
  33. }
  34.  
  35. //////////////////
  36. // Sort an array of pointers to CmpObj objects.
  37. // This is what callers use to sort an array.
  38. //
  39. void CmpObj::Sort(CmpObj** array, int len)
  40. {
  41.     qsort(array, len, sizeof(CmpObj*), QSortFn);
  42. }
  43.  
  44. //////////////////
  45. // Now Person is derived from CmpObj, because
  46. // Persons are comparable objects.
  47. //
  48. class Person : public CmpObj {
  49.     char name[20];
  50. public:
  51.     Person(const char* n)    { strcpy(name, n); }
  52.     void print()                { cout << name << '\n'; };
  53.     int compare(CmpObj* c2);
  54. };
  55.  
  56. //////////////////
  57. // Compare function for Person just compares name strings.
  58. //
  59. int Person::compare(CmpObj* p2)
  60. {
  61.     return strcmp(name, ((Person*)p2)->name);
  62. }
  63.  
  64. // Some sample people (unsorted).
  65. Person people[] = {
  66.     { "Cynthia" },
  67.     { "Sandy" },
  68.     { "Carl" },
  69.     { "Alfred" },
  70.     { "Beth" },
  71. };
  72. const NPEOPLE = sizeof(people)/sizeof(Person);
  73.  
  74. /////////////////
  75. // Main program loop: 
  76. // create array of pointers, sort it, then print.
  77. // 
  78. int main(int, char**)
  79. {
  80.     Person *array[NPEOPLE];
  81.  
  82.     // Initialize array of pointers from sample Persons
  83.     for (int i=0; i<NPEOPLE; i++)
  84.         array[i] = &people[i];
  85.  
  86.     // sort the array
  87.     CmpObj::Sort((CmpObj**)array, NPEOPLE);
  88.  
  89.     // print
  90.     for (i=0; i<NPEOPLE; i++)
  91.         array[i]->print();
  92.  
  93.     return 0;
  94. }
  95.